package com.kehutong.common.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils;
import org.coraframework.inject.Singleton;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Singleton
public class TimestampConverter implements Converter<Timestamp> {


    @Override
    public Class<Timestamp> supportJavaTypeKey() {
        return Timestamp.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Timestamp convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException {
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            return Timestamp.valueOf(cellData.getStringValue());
        } else {
            Date date = DateUtils.parseDate(cellData.getStringValue(),contentProperty.getDateTimeFormatProperty().getFormat());
            return new Timestamp(date.getTime());
        }
    }


    @Override
    public CellData convertToExcelData(Timestamp value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration){
        SimpleDateFormat dateFormat;
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else {
            dateFormat = new SimpleDateFormat(contentProperty.getDateTimeFormatProperty().getFormat());
        }
        String date = dateFormat.format(value);
        return new CellData<>(date);
    }
}